package com.tanx.entity.system;

import com.tanx.context.BeanProvider;
import com.tanx.dao.UserOperationLogRepository;
import com.tanx.entity.User;
import com.tanx.entity.UserAccount;
import com.tanx.utils.UuidGenerator;
import org.apache.shiro.SecurityUtils;

import javax.persistence.*;
import java.util.Date;

/**
 * 系统日志,由aop自动生成
 * Created by 唐旭 on 2015/7/8.
 */
@Entity
@Table(name = "t_UserOperationLog")
public class UserOperationLog {
    private transient UserOperationLogRepository repository =
            BeanProvider.getBean(UserOperationLogRepository.class);

    /**
     * 日志id
     */
    @Id
    private String uuid = UuidGenerator.generate();
    /**
     * 日志描述,日志的事件
     */
    @Column
    private String description;
    /**
     * 发生时间
     */
    @Column
    @Temporal(TemporalType.TIMESTAMP)
    private Date date;
    /**
     * 操作用户
     */
    @ManyToOne
    @JoinColumn(name = "user_id")
    private User user;


    public UserOperationLog() {
    }

    /**
     * 创建一个用户操作日志对象
     *
     * @param description 描述
     */
    public UserOperationLog(String description) {
        this(((UserAccount) SecurityUtils.getSubject().getSession().getAttribute("user")).getUser()
                , new Date(), description);
    }

    /**
     * 创建一个用户操作日志对象
     *
     * @param user        当前用户
     * @param date        时间
     * @param description 描述
     */
    public UserOperationLog(User user, Date date, String description) {
        this.user = user;
        this.date = date;
        this.description = description;
    }


    public String getUuid() {
        return uuid;
    }

    public UserOperationLog setUuid(String uuid) {
        this.uuid = uuid;
        return this;
    }

    public String getDescription() {
        return description;
    }

    public UserOperationLog setDescription(String description) {
        this.description = description;
        return this;
    }

    public Date getDate() {
        return date;
    }

    public UserOperationLog setDate(Date date) {
        this.date = date;
        return this;
    }

    public User getUser() {
        return user;
    }

    public UserOperationLog setUser(User user) {
        this.user = user;
        return this;
    }

    public UserOperationLog save() {
        System.out.println(this);


        repository.save(this);
        return this;
    }

    @Override
    public String toString() {
        return String.format("[%s][%s][%s(%s)]-%s",
                date.toString(), uuid , user == null ? "Unknown User" : user.getName(),
                user == null ? "Unknown User UUID" : user.getUuid(), description);
    }
}
